package com.harmontronics.hanma.paas.paas.exception;


import com.harmontronics.hanma.paas.paas.common.ResponseEntity;
import com.harmontronics.hanma.paas.paas.consts.BaseI18nKeyEnum;
import com.harmontronics.hanma.paas.paas.utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 公用controller层异常处理
 *
 * @author Chasen
 */
@RestControllerAdvice
@Slf4j
public class ControllerExceptionHandler {

  /** 处理自定义异常 */
  @ExceptionHandler(ErrorKeyException.class)
  public ResponseEntity handleErrorKeyException(ErrorKeyException e) {
    return ResponseEntity.error(e.getErrorCode(), RequestUtils.localeMessage(e.getI18nKey(),e.getMessageData()),e.getMessageData());
  }

  /** 处理自定义异常 */
  @ExceptionHandler(HttpErrorException.class)
  public ResponseEntity handleHttpErrorException(HttpErrorException e) {
    return ResponseEntity.error(-1000,e.toString());
  }

  @ExceptionHandler(Throwable.class)
  public ResponseEntity handleException(Throwable e) {
    log.error(e.getMessage(), e);
    return ResponseEntity.error(BaseI18nKeyEnum.SYSTEM_ERROR);
  }

  @ExceptionHandler(DataAccessResourceFailureException.class)
  public ResponseEntity handleDataAccessResourceFailureException(DataAccessResourceFailureException e) {
    log.error(e.getMessage(), e);
    return ResponseEntity.error(BaseI18nKeyEnum.DB_QUERY_TIMEOUT);
  }
}
